#include <TFT_eSPI.h>
#include <TimeLib.h>
#include "setting.h"
#include "img.h"
#include "font.h"
#include "jsonConf.h"
#include <ESP8266WiFi.h>
#include <FS.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include <ESPAsyncWebServer.h>
#include <LittleFS.h>

/**
   接线端口  14 13 16 05 01

  NODEMCU
   D5 D7 D2 D3 D1
*/

TFT_eSPI tft = TFT_eSPI();
WiFiClient wifiClient;
AsyncWebServer server(80);

int startPoints[6];
uint16_t colors[5];

uint8_t back_light = 255;
bool diminish = true;

void setup()
{
    Serial.begin(115200);
    delay(500);
    Serial.println("begin ...");
    tft.init(); //初始化
    tft.fillScreen(TFT_BLACK);
    tft.setSwapBytes(true);

    if (!SPIFFS.begin())
    {
        tft.println("open SPIFFS error..");
        return;
    }
    tft.println("open SPIFFS success..");
    delay(500);
    // 读取 wifi sta配置
    if (loadJsonConf(CONF_FILE_NAME))
    {
        tft.println("start wifi STA...");
        UserConf conf = getUserConf();
        tft.println(conf.sid);
        tft.println(conf.pass);
        wifiBegin(conf.sid, conf.pass);

        // wifi 已经链接
        if (WiFi.status() == WL_CONNECTED)
        {
            tft.fillScreen(TFT_BLACK);
            getTimeNow();
            getWatherNow(conf.wather_key, conf.localation);
            getDAily(conf.wather_key, conf.localation);
            getLife(conf.wather_key, conf.localation);
            showDate(0);
            showTime(20);
            showWather(70, WATHER_CODE, WATHER_TEMPERATURE);
            watherToday(142, 0);
            showLife(117, 0);
            //    tft.fillRect(90, 70, 38, 90, TFT_GREEN);
            mygifinit();
            //      drawgifText(0);
        }
        else
        {
            // wifi 链接失败启动AP 模式
            tft.println("wifi not connection..");
            startWiFiAp();
        }
    }
    else
    {
        tft.println("not have setting file..");
        // 加载html 页面文件
        startWiFiAp();
    }
}

void startWiFiAp()
{

    tft.println("start wifi AP...");
    // 开启你配置网络
    servletSet();
    server.begin();
    SETTING_PAGE = loadFile(SETTING_FILE_NAME);
    Serial.println(">>>>>加载配置WIFI页面完成");
    startApServer();
    tft.println("wifi ap server sid:");
    tft.println(String(AP_SSID));
    tft.println("setting page:");
    tft.println("192.168.10.1");
}
unsigned int i = 0;

int __date = -1;
int __hour = -1;
int __min = -1;
int __sec = -1;
int __watherCode = -1;
int __temp = 9999;

void showWather(int y, int code, int temp)
{
    if (__watherCode != code)
    {
        __watherCode = code;
        showWatherImg(code, 0, y);
        showCnWather(code, 45, y, WATHER_COLOR);
    }

    if (temp != __temp)
    {
        __temp = temp;
        //   tft.setTextColor(TFT_GREEN, TFT_BLACK);
        String _t;
        tft.setTextColor(TEMPERATURE_COLOR, TFT_BLACK);
        tft.fillRect(45, y + 20, 88, 20, TFT_BLACK);
        _t = String(temp);
        int _x = 45;
        if (_t.length() == 1)
            _x = _x + 10;
        else if (_t.length() == 2)
            _x = _x + 20;
        else if (_t.length() == 3)
            _x = _x + 30;
        else
            _x = _x + 40;

        tft.drawString(_t, 45, y + 20, 2);
        tft.drawBitmap(_x, y + 20, hz_duC, 16, 16, TEMPERATURE_COLOR);
    }
}
void showTime(int y)
{
    if (hour() != __hour)
    {
        __hour = hour();
        tft.setTextColor(HOURE_COLOR, TFT_BLACK);
        String _h;
        if (hour() > 9)
            _h = String(hour());
        else
            _h = "0" + String(hour());
        tft.drawString(_h, 2, y, 6);

        backLight();
    }
    if (second() % 2 == 1)
    {
        tft.setTextColor(SECOND_COLOR, TFT_BLACK);
        tft.drawString(":", 56, y, 6);
    }
    else
    {
        tft.fillRect(56, y, 16, 48, TFT_BLACK);
    }

    if (minute() != __min)
    {
        __min = minute();
        tft.setTextColor(MIN_COLOR, TFT_BLACK);
        String _m;
        if (minute() > 9)
            _m = String(minute());
        else
            _m = "0" + String(minute());
        tft.drawString(_m, 72, y, 6);
    }
}

void showDate(int y)
{
    // 年月日
    int s = now() / 60 / 60 / 24;
    if (s != __date)
    {
        String date = String(year()) + "-" + MONTH_NAMES[month() - 1] + "-" + String(day());
        __date = s;
        tft.setTextColor(DATE_COLOR, TFT_BLACK);
        tft.fillRect(0, y, 128, 20, TFT_BLACK);

        //    String week = WDAY_NAMES[weekday() - 1];
        tft.drawString(date, 0, y, 2);

        //    tft.drawString(week, 98 , y, 2);
        showWeek(weekday() - 1, 88, y, WEEK_COLOR);
        // 星期
    }
}

void showLife(int y, int b)
{
    uint16_t color = LIFE_COLOR;
    int a = b % 6;
    tft.fillRect(0, y, 90, 20, TFT_BLACK);

    switch (a)
    {
    case 0:
        lifeCarw(0, y, LIFE_COLOR_TITLE, color, LIFE_CAR_WASHINNG);
        break;
    case 1:
        lifeDRESSING(0, y, LIFE_COLOR_TITLE, color, LIFE_DRESSING);
        break;
    case 2:
        lifeFLU(0, y, LIFE_COLOR_TITLE, color, LIFE_FLU);
        break;
    case 3:
        lifeSport(0, y, LIFE_COLOR_TITLE, color, LIFE_SPORT);
        break;
    case 4:
        lifeTRAVEL(0, y, LIFE_COLOR_TITLE, color, LIFE_TRAVEL);
        break;
    case 5:
        lifeUV(0, y, LIFE_COLOR_TITLE, color, LIFE_UV);
        break;
    }
}

void watherToday(int16_t y, int b)
{
    int a = b % 7;
    tft.fillRect(0, y, 90, 20, TFT_BLACK);
    tft.setTextColor(TODAY_VALUE_COLOR, TFT_BLACK);
    switch (a)
    {
    case 0:
        tft.drawBitmap(0, y, hz_bai, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, hz_tian, 16, 16, TODAY_TITLE_COLOR);
        showCnWather(TOMORROW_DAY_CODE, 36, y, TODAY_VALUE_COLOR);
        break;
    case 1:
        tft.drawBitmap(0, y, YE_16, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, WAN_16, 16, 16, TODAY_TITLE_COLOR);
        showCnWather(TOMORROW_NIGHT_CODE, 36, y, TODAY_VALUE_COLOR);
        break;
    case 2:
    {
        tft.drawBitmap(0, y, WEN_16, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, DU_16, 16, 16, TODAY_TITLE_COLOR);
        String __t = TOMORROW_LOW_TEMPERATURE + " - ";
        __t = __t + TOMORROW_HUMIDITY;
        tft.drawString(__t, 36, y, 2);
        break;
    }
    case 3:
        tft.drawBitmap(0, y, hz_feng, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, SU_16, 16, 16, TODAY_TITLE_COLOR);
        tft.drawString(TOMORROW_WIND_SPEED, 36, y, 2);
        break;
    case 4:
        tft.drawBitmap(0, y, hz_feng, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, LI_16, 16, 16, TODAY_TITLE_COLOR);
        tft.drawString(TOMORROW_WIND_SCALE, 36, y, 2);
        break;
    case 5:
        tft.drawBitmap(0, y, hz_feng, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, XIANG_16, 16, 16, TODAY_TITLE_COLOR);
        drawWIND(36, y, TOMORROW_WIND_DIRECTION, TODAY_VALUE_COLOR);
        break;
    case 6:
        tft.drawBitmap(0, y, SHI1_16, 16, 16, TODAY_TITLE_COLOR);
        tft.drawBitmap(16, y, DU_16, 16, 16, TODAY_TITLE_COLOR);
        tft.drawString(TOMORROW_HUMIDITY, 36, y, 2);
        break;
    }
}
void mygifinit()
{
    for (int i = 0; i < 6; i++)
    {
        int randTemp = random(90, 150);
        startPoints[i] = randTemp;
    }
    int stR = 0;
    int stG = 255;
    int stB = 0;
    for (int i = 0; i < 5; i++)
    {
        int tempR = (float)stR * map(i, 4, 0, 10, 4) / 10;
        int tempG = (float)stG - 50 * i;
        int tempB = (float)stB * map(i, 4, 0, 10, 4) / 10;
        uint16_t temp565 = tft.color565(tempR, tempG, tempB);
        colors[i] = temp565;
    }
}

// int __gifsp = 90;
void drawgifText()
{
    // 90, 70, 38, 90,
    for (int i = 0; (i * 8 + 90) < 128; i++)
    {
        int xPos = i * 8 + 90;     // 起始X位置
        int yPos = startPoints[i]; //起始Y位置
        int line = random(1, 4);   // 列字符长度
        tft.fillRect(xPos, yPos, 8, 8, TFT_BLACK);
        for (int j = 0; j < line; j++)
        {
            yPos = yPos + 8;
            if (yPos > 159)
                yPos = 90;
            uint16_t colorTemp = colors[j + 1];
            tft.setTextColor(colorTemp);
            tft.fillRect(xPos, yPos, 8, 8, TFT_BLACK);
            tft.drawChar(random(48, 50), xPos, yPos, 1);

            //    tft.fillRect(96, 100+j*8, (j+1)*8, 8, TFT_BLACK);
            //    tft.drawString(String(yPos), 96, 100+j*8, 1);
        }
        startPoints[i] = startPoints[i] + 8; // 下次移动初始位置
        if (startPoints[i] > 159)
            startPoints[i] = 90;
    }
}
void backLight()
{

//  if (diminish){
//       back_light-=5;
//     }else{
//       back_light+=5;
//     }
//     if (back_light <= 0){
//       diminish = false;
//       back_light = 0;
//     }
//     else if (back_light >= 255){
//       diminish = true;
//       back_light = 255;
//     }
//     analogWrite(TFT_BL, back_light);

    if (hour() > 6 && hour() < 22)
        analogWrite(TFT_BL, 255);
    else
        analogWrite(TFT_BL, 100);
}

unsigned long interval1 = 5000;
unsigned long interval2 = 300000;

unsigned long _p1 = 0;
unsigned long _p2 = 0;
unsigned int _iif = 1;
long wifiScanTime = 30000;
unsigned long _wifiscan = 0;
int gif = 200;
unsigned long _gifp = 0;

void loop()
{
    unsigned long currentMillis = millis();

    if (currentMillis - _wifiscan >= wifiScanTime)
    {
        _wifiscan = currentMillis;
        wifiScan();
    }

    if (WiFi.status() != WL_CONNECTED)
    {
        return;
    }
    showDate(0);
    showTime(20);
    if (currentMillis - _p2 >= interval2)
    {
        _p2 = currentMillis;

        UserConf conf = getUserConf();
        getTimeNow();
        getWatherNow(conf.wather_key, conf.localation);
        getDAily(conf.wather_key, conf.localation);
        getLife(conf.wather_key, conf.localation);

        showWather(70, WATHER_CODE, WATHER_TEMPERATURE);
    }

    if (currentMillis - _p1 >= interval1)
    {
        _p1 = currentMillis;
        showLife(142, _iif);
        watherToday(117, _iif);
        _iif++;
        if (_iif > 20000)
            i = 0;
    }

    if (currentMillis - _gifp >= gif)
    {
        _gifp = currentMillis;
        drawgifText();
     //   backLight();
    }
}
